package cn.e4j.core.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 微信通用调用处理类
 * 包括第三方接口调用配置地址
 * Created by wenchuan.li on 2018-9-7.
 */
public class OkHttp {
    private static Logger logger = LoggerFactory.getLogger(OkHttp.class);

    private static OkHttpClient okClient = new OkHttpClient();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    //public static final String URL = "http://wxqyh.digiwin.com.cn:8009/crm-wx-sanmu/wx/i";

    public static final String URL = "http://localhost:9019/wx/wx/i";

    public static JSONObject okPost(String url, String json) throws Exception {

        String accessData = "";
        okClient = new OkHttpClient().newBuilder().connectTimeout(50000, TimeUnit.MILLISECONDS)
                .readTimeout(50000, TimeUnit.MILLISECONDS)
                .build();
        Request.Builder request = new Request.Builder()
                .url(url)
                //.header("digi-middleware-auth-app", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDUxMTYyNjkyMjcsInNpZCI6ODIyMDIzMzgxOTg0NjE5NjU3LCJpZCI6IndlQ2hhdEVudGVycHJpc2UifQ.EckIfflS2Wc82jyxjgQkdK7x8Rjc6TyYM02Qh-hAFE8")
                //.header("Accept-Charset","utf-8")
                //.header("Content-Type","application/json")
                .post(RequestBody.create(JSON, json));

//        if (!AppUtils.isEmpty(accessData)) {
//            JSONObject token = JSONObject.parseObject(accessData);
//            request.header("digi-middleware-auth-access", token.getString("token"));
//            request.header("accesstoken", token.getString("token"));
//        }

        Response response = okClient.newCall(request.build()).execute();
        String r = response.body().string();
        logger.debug("API URL: {}", url);
        logger.debug("API params: {}", json);
        logger.debug("API Response: {}", r);
        return JSONObject.parseObject(r).getJSONObject("response");
    }

    public static JSONObject okGet(String url) throws Exception {
        Request.Builder request = new Request.Builder()
                .url(url);

        Response response = okClient.newCall(request.build()).execute();
        String r = response.body().string();
        logger.debug("API URL: {}",  url);
        logger.debug("API Response: {}",  r);
        return JSONObject.parseObject(r);
    }

    public static JSONObject upload(String url, byte[] content, String fileName) throws Exception {
        // TODO
        //String accessData = (String) UserUtils.getCache(AccessTokenFilter.cacheKey);
        String accessData = "";

        MediaType type = MediaType.parse("application/octet-stream");
        RequestBody fileBody = RequestBody.create(type, content);

        RequestBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addPart(Headers.of(
                        "Content-Disposition", "form-data; name=\"attach\"; filename=\"" + fileName + "\"")
                        , fileBody).build();

        Request.Builder request = new Request.Builder()
                .url(url)
                .header("digi-middleware-auth-app", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MDUxMTYyNjkyMjcsInNpZCI6ODIyMDIzMzgxOTg0NjE5NjU3LCJpZCI6IndlQ2hhdEVudGVycHJpc2UifQ.EckIfflS2Wc82jyxjgQkdK7x8Rjc6TyYM02Qh-hAFE8")
                .post(multipartBody);

//        if (!AppUtils.isEmpty(accessData)) {
//            JSONObject token = JSONObject.parseObject(accessData);
//            request.header("digi-middleware-auth-access", token.getString("token"));
//            request.header("accesstoken", token.getString("token"));
//        }

        Response response = okClient.newCall(request.build()).execute();
        String r = response.body().string();
        logger.debug("API URL: {}", url);
        logger.debug("API Response: {}", r);
        return JSONObject.parseObject(r);
    }


}
